package com.dding.cms.base.web.widget.handler;

import static com.dding.cms.base.web.ActionConstants.ATTACHMENTFILENAMES;
import static com.dding.cms.base.web.ActionConstants.ATTACHMENTNAMES;
import static com.dding.cms.base.web.ActionConstants.ATTACHMENTPATHS;
import static com.dding.cms.base.web.ActionConstants.ATTACHMENT_TABLE_NAME;
import static com.dding.cms.base.web.ActionConstants.DEFAULT_CHANGE_FIELDS;
import static com.dding.cms.base.web.ActionConstants.UPDATE_DATA_MAP;
import static com.dding.cms.base.web.ActionConstants.WIDGET_ATTACHMENT_ID;
import static com.dding.cms.base.web.ActionConstants.WIDGET_REMOVE_ID_KEY;
import static com.dding.cms.base.web.ActionConstants.WIDGET_RESULT_KEY;
import static com.dding.cms.base.web.ActionConstants.WIDGET_TYPE_ATTACHMENT;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;

import com.dding.cms.base.entity.ContentAttachment;
import com.dding.cms.base.web.bo.ContentAttachmentBO;
import com.dding.cms.base.web.util.Utils;
import com.dding.cms.base.web.widget.IWidgetContext;
import com.dding.cms.base.web.widget.WidgetTable;

@WidgetTable(ATTACHMENT_TABLE_NAME)
public class AttachmentHandler extends AbstractWidgetHandler {

	private static final String ATTACHMENTID = "attachmentId";

	@Override
	public Object handleSet(IWidgetContext widgetContext) {

		List<Model> list = new ArrayList<Model>();
		List<String> ids = new ArrayList<String>();

		Map<String, Object> result = new HashMap<String, Object>();
		result.put(WIDGET_RESULT_KEY, list);
		result.put(WIDGET_REMOVE_ID_KEY, ids);

		Map<String, Object> para = widgetContext.getParameters();
		String[] paths = getParameterSetValue(ATTACHMENTPATHS,
				WIDGET_TYPE_ATTACHMENT, para, ids);

		if (paths == null || paths.length == 0)
			return result;

		String[] fileNames = getParameterSetValue(ATTACHMENTFILENAMES,
				WIDGET_TYPE_ATTACHMENT, para, ids);
		String[] names = getParameterSetValue(ATTACHMENTNAMES,
				WIDGET_TYPE_ATTACHMENT, para, ids);

		for (int i = 0; i < paths.length; i++) {
			ContentAttachment attachment = new ContentAttachment();
			attachment.set("priority", i + 1);
			attachment.set("attachment_path", paths[i]);
			attachment.set("attachment_name", names[i]);
			attachment.set("filename", fileNames[i]);
			attachment.set("download_count", 0);
			list.add(attachment);
		}
		return result;
	}

	@Override
	public Object handleGet(IWidgetContext widgetContext) {
		Map<String, Object> map = widgetContext.getParameters();
		Map<String, List<ContentAttachmentBO>> result = new HashMap<String, List<ContentAttachmentBO>>();
		List<ContentAttachmentBO> attachments = new ArrayList<ContentAttachmentBO>();
		for (Object object : map.values()) {
			if (object instanceof LazyList) {
				@SuppressWarnings("unchecked")
				LazyList<? extends Model> list = (LazyList<? extends Model>) object;
				for (Iterator<? extends Model> iterator = list.iterator(); iterator
						.hasNext();) {
					Model model = iterator.next();
					ContentAttachmentBO bo = (ContentAttachmentBO) Utils
							.buildBO(model, ContentAttachmentBO.class);
					attachments.add(bo);
				}
			}
		}
		result.put(WIDGET_ATTACHMENT_ID, attachments);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object handleUpdateAssociation(IWidgetContext widgetContext) {

		Map<String, Object> data = widgetContext.getParameters();

		Set<String> fields = (Set<String>) data.get(DEFAULT_CHANGE_FIELDS);

		if (fields == null || fields.size() == 0)
			return null;

		Map<String, Object> dataMap = (Map<String, Object>) data
				.get(UPDATE_DATA_MAP);
		String content_id = ((String[]) dataMap.get("content_id"))[0];

		String[] paths = getParameterSetValue(ATTACHMENTPATHS,
				WIDGET_TYPE_ATTACHMENT, dataMap, null);

		LazyList<Model> listAttachments = ContentAttachment.find(
				"content_id = ?", new Object[] { content_id });

		deleteAll(listAttachments);

		if (paths == null || paths.length == 0) {
			return null;
		}

		String[] names = getParameterSetValue(ATTACHMENTNAMES,
				WIDGET_TYPE_ATTACHMENT, dataMap, null);
		String[] fileNames = getParameterSetValue(ATTACHMENTFILENAMES,
				WIDGET_TYPE_ATTACHMENT, dataMap, null);

		Iterator<String> it = fields.iterator();
		while (it.hasNext()) {
			String field = it.next();
			if (field.startsWith(ATTACHMENTID)) {
				for (int i = 0; i < paths.length; i++) {
					ContentAttachment attachment = new ContentAttachment();
					attachment.set("priority", i + 1);
					attachment.set("attachment_path", paths[i]);
					attachment.set("attachment_name", names[i]);
					attachment.set("filename", fileNames[i]);
					attachment.set("download_count", 0);
					attachment.set("content_id", content_id);
					attachment.save();
				}
				it.remove();
				break;
			}
		}
		return null;
	}

	private void deleteAll(List<Model> listAttachments) {
		if (listAttachments.size() != 0) {
			for (Iterator<Model> iterator = listAttachments.iterator(); iterator
					.hasNext();) {
				Model model = iterator.next();
				model.delete();
			}
		}
	}
}
